import pytest
import os,sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from common import read_config
from common.pwd_encode import Encryptor
from common.pwd_encode import Encryptor
from common.util import get_resp, assert_response
from common.util import data_path
from common.read_yaml import clear_yaml, get_yaml_data, write_yaml, replace_content
from common.request_0 import HttpRequest

session = HttpRequest()
cof = read_config.Docof()
data = get_yaml_data(data_path + '/login_token.yaml')['login'][0]
temp_token = get_yaml_data(data_path + '/login_token.yaml')['Temporary token'][0]
# start-密码加密判断
ncry = get_yaml_data(data_path + '/login_token.yaml')['Password encryption'][0]['type']
values = get_yaml_data(data_path + '/login_token.yaml')['Password encryption'][0]['values']
key = Encryptor()
body = data['json']
if ncry:
    body['password'] = getattr(key, ncry)(*values)  # 赋值
# end-密码加密判断
ex = data['execute']
_api_name = data['title']
if cof.get_value_from_option('environment','execute') == "tf_project":
    host = cof.get_value_from_option('environment','tf_project')
elif cof.get_value_from_option('environment','execute') == "demo_project":
    host = cof.get_value_from_option('environment','demo_project')
url = host+data['request']['url']
method = data['request']['method']
token = data['extract_data']
expected = data['expected']
print(body)


# #
@pytest.fixture(scope="session", autouse=True)  # 默认是函数级别  如果不添加 session  则会在每条用例都执行一次 前置和后置操作
def excuhte_data():
    print('请求的前置')
    if ex == True:
        print(ex)
        re = session.request(method, url, body)
        assert_response(re, expected, _api_name)
        get_resp(re, token, _api_name)  # 提取token数据

    elif temp_token:
        # new_dict = {'Authorization': temp_token}  # 读取yaml文件的临时认证  写入到关联文件
        # write_yaml(new_dict)  # 第一次需要写入 因为当文件为空  不会被当成字典
        replace_content(temp_token)  # 此方式可以替换相同的字典 如果数据不存在则写入

    else:
        print("未获取token")
    yield
    clear_yaml()
    print("请求后置------清理关键字数据")
if __name__ == '__main__':
    excuhte_data()
